class Favorite < ActiveRecord::Base
  belongs_to :user
  belongs_to :resource
  
  def Favorite.addFavorite(userId, resourceId)
  query = "SELECT * FROM favorites WHERE resource_id = #{resourceId} AND user_id = #{userId};"
  favorite = Favorite.find_by_sql(query)
  puts "***************** "+ (favorite.length).to_s
  if(favorite.length == 0) then
  	favorite = Favorite.new
  	favorite.user_id = userId
  	favorite.resource_id = resourceId
  	favorite.save
  end
  end

  def Favorite.deleteFavorite(userId, resourceId)
#   query = "SELECT * FROM favorites WHERE resource_id = #{resourceId} AND user_id = #{userId};"
  favorite = Favorite.find(:first , :conditions => "resource_id = #{resourceId} AND user_id = #{userId}")
	favorite.destroy
  end

  def getFavorites(userId)
    query = "SELECT * FROM favorites WHERE user_id = #{userId};"
    favourites = Favorite.find_by_sql(query)
    conditions = ""
    favourites.each do |f|
        conditions << "id = '#{f.resource_id}' OR "
    end
    resources = Resource.find(:all, :conditions => conditions+"id < '0'") 
                      #id<0 is written just to have a false condition after the last OR
    return resources
  end

def Favorite.isAFavorite(userId,resourceId)
	isFavorite = false
	favorite = Favorite.find(:first , :conditions => "user_id = #{userId} AND resource_id = #{resourceId}")
	isFavorite = true if(not favorite.nil?)
	return isFavorite
end
end
